<template>
  <Dialog :appDialog="appDialog">
    <el-form ref="ruleFormRef" :model="formData" class="form-box" :rules="rules">
      <el-form-item label="来源名称" prop="name">
        <el-input maxlength="15" style="width: 280px" show-word-limit v-model="formData.name" placeholder="请输入来源名称"></el-input>
      </el-form-item>
      <el-form-item label="显示状态" prop="status">
        <el-switch v-model="formData.status" :active-value="1" :inactive-value="2" />
        <div class="desc">开启后，可为线索的来源设置为该来源</div>
      </el-form-item>
    </el-form>
  </Dialog>
</template>

<script setup lang="ts">
  import { sourceCreate, sourceEdit } from '@/api/customer/clubManage/clueSource'
  import Dialog from '@/components/Dialog.vue'
  import type { FormInstance } from 'element-plus'
  import { ElMessage } from 'element-plus'
  import { ref, watch } from 'vue'
  const ruleFormRef = ref<FormInstance>()
  const emit = defineEmits(['refresh'])
  const rules = ref({
    name: { required: true, message: '请输入来源名称', trigger: 'blur' },
    status: { required: true, message: '显示状态', trigger: 'blur' }
  })
  const formData = ref({
    name: '',
    status: 1
  })

  const cancelHandel = () => {
    ruleFormRef.value.resetFields()
    appDialog.value.visible = false
    formData.value.name = ''
    formData.value.status = 1
  }

  const submitHandel = () => {
    ruleFormRef.value.validate(async (valid, fields) => {
      if (valid) {
        if (appDialog.value.editInfo.id) {
          await sourceEdit({ ...formData.value, source_id: appDialog.value.editInfo.id })
          emit('refresh')
          cancelHandel()
          ElMessage({
            type: 'success',
            message: '修改成功'
          })
        } else {
          await sourceCreate({ ...formData.value })
          emit('refresh')
          cancelHandel()
          ElMessage({
            type: 'success',
            message: '创建成功'
          })
        }
      }
    })
  }
  const appDialog = ref({
    visible: false,
    title: '新增线索来源',
    width: '600px',
    cancel: cancelHandel,
    submit: submitHandel,
    cancelText: '取消',
    submitText: '确认',
    editInfo: {}
  })

  // 编辑就赋值
  watch(
    () => appDialog.value.visible,
    (val: any) => {
      if (val) {
        if (appDialog.value.editInfo.id) {
          appDialog.value.title = '编辑线索来源'
          formData.value = Object.assign(formData.value, appDialog.value.editInfo)
        } else {
          appDialog.value.title = '新增线索来源'
          formData.value = {
            name: '',
            status: 1
          }
        }
      }
    }
  )

  defineExpose({ appDialog })
</script>

<style lang="scss" scoped>
  .form-box {
    margin-top: 14px;
    height: 218px;
    .icon {
      margin-left: 6px;
      vertical-align: middle;
    }
    .tip-desc {
      font-size: 12px;
      font-family: PingFangSC-Regular, PingFang SC;
      font-weight: 400;
      color: #ffffff;
      line-height: 20px;
    }
  }
</style>
